package jwebtester.dal.provider.impl;

import infrastructure.Scopes;

import java.util.ArrayList;
import java.util.List;

import jwebtester.business.services.MapperService;
import jwebtester.dal.entities.ExpertGroupEntity;
import jwebtester.dal.provider.ExpertGroupsDataProvider;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import utils.CollectionUtils;
import domain.entities.ExpertGroup;

@Repository
@Scope(value = Scopes.Request, proxyMode = ScopedProxyMode.INTERFACES)
public class ExpertGroupsDataProviderImpl implements ExpertGroupsDataProvider {

	private static final Logger LOG = LoggerFactory.getLogger(ExpertGroupsDataProviderImpl.class);

	@Autowired
	private transient SessionFactory sessionFactory;

	@Autowired
	private transient MapperService mapperService;

	@Override
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public List<ExpertGroup> getExpertGroups(int organizationID) {
		Session session = sessionFactory.getCurrentSession();

		try {
			final List<ExpertGroup> result = new ArrayList<ExpertGroup>();

			final Query query = session
					.createQuery("from ExpertGroupEntity eg where eg.organizationEntity.id = :orgID");
			query.setInteger("orgID", organizationID);

			List<ExpertGroupEntity> dataEntities = CollectionUtils.castList(query.list());
			for (ExpertGroupEntity dataEntity : dataEntities) {
				ExpertGroup expertGroup = (ExpertGroup) mapperService.mapTo(dataEntity,
						ExpertGroup.class);
				result.add(expertGroup);
			}

			return result;
		} catch (RuntimeException ex) {
			LOG.error(String.format("Error loading expert group for organization. ID=%s",
					organizationID), ex);
			throw ex;
		}
	}

}
